<?php

namespace App\Module\Api\Controllers;

use App\Exceptions\Customize\ParamsException;
use App\Module\Api\Controllers\Request\UserBindMobileRequest;
use App\Module\Api\Validator\UserBindMobileValidator;
use App\System\Base\Repositories\BaseSmsCodeRepository;
use App\System\Base\Services\TokenService;
use App\System\Cis\Repositories\CisUserRepository;
use Illuminate\Support\Facades\DB;

/**
 *更新手机号
 */
class UserBindMobileController extends Controller
{

    public function __construct()
    {
        $this->query = new UserBindMobileRequest();
        parent::__construct();

    }

    public function index()
    {
        (new UserBindMobileValidator())->check();
         $user_id = TokenService::getUserId();
         $masterId = TokenService::getMasterId();
        $smsCode = BaseSmsCodeRepository::getInstance();
        $check_code = $smsCode->getOneById($this->query->smscodeId,1);
        if($check_code['s'])
        {
            return apiResponse($check_code);
        }
        DB::beginTransaction();
        $user = CisUserRepository::getInstance();

        $check = $user->getMasterUser($this->query->mobile);
        if($check){
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '绑定失败，手机号已存在',
            ]);
        }
        $res = $user->updateMobile($masterId,$this->query->mobile);
        if(!$res)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '绑定失败，服务内部异常',
            ]);
        }
        DB::commit();
        return apiResponse();
    }
}
